//SPDX-FileCopyrightText: Copyright 2022-2024 深圳市同心圆网络有限公司
//SPDX-License-Identifier: GPL-3.0-only

import { Descriptions, Layout, Tooltip, Tree } from "antd";
import React, { useEffect, useState } from "react";
import type { LocalRepoDirTreeNode, LocalRepoCodeCountInfo } from "@/api/local_repo";
import { list_tree_dir, count_code } from "@/api/local_repo";
import type { DataNode } from "antd/lib/tree";
import { resolve } from "@tauri-apps/api/path";
import { Cell, Pie, PieChart } from "recharts";
import { useSize } from "ahooks";

export interface CountAnalyseProps {
    repoPath: string;
}

const COLORS = ['#0088FE', '#00C49F', '#FFBB28', '#FF8042'];

const CountAnalyse = (props: CountAnalyseProps) => {
    const winSize = useSize(window.document.body);

    const [dirTree, setDirTree] = useState<DataNode[]>([]);
    const [countList, setCountList] = useState<LocalRepoCodeCountInfo[]>([]);

    const [curTreeKey, setCurTreeKey] = useState("");

    const processTreeNode = (curNode: LocalRepoDirTreeNode, curPath: string[], resultList: DataNode[]) => {
        const curDataNode: DataNode = {
            key: [...curPath, curNode.name].filter(item => item != "").join("/"),
            title: curPath.length == 0 ? "代码目录" : curNode.name,
        };
        resultList.push(curDataNode);
        if (curNode.childrens.length == 0) {
            return;
        }
        curDataNode.children = [];
        for (const subNode of curNode.childrens) {
            processTreeNode(subNode, [...curPath, curNode.name], curDataNode.children);
        }
    };

    const loadDirTree = async () => {
        const rootNode = await list_tree_dir(props.repoPath);
        const tmpList = [] as DataNode[];
        processTreeNode(rootNode, [], tmpList);
        setDirTree(tmpList);
    };

    const loadCountList = async () => {
        setCountList([]);
        const subPath = await resolve(props.repoPath, curTreeKey);
        const res = await count_code(props.repoPath, subPath);
        setCountList(res);
    };

    useEffect(() => {
        loadDirTree();
    }, [props.repoPath]);

    useEffect(() => {
        loadCountList();
    }, [props.repoPath, curTreeKey]);

    return (
        <Layout>
            <Layout.Sider theme="light" width={250} style={{ height: "calc(100vh - 60px)", overflowY: "scroll", padding: "10px 10px", overflowX: "hidden", borderRight: "1px solid #e4e4e8" }}>
                {dirTree.length > 0 && (
                    <Tree selectedKeys={[curTreeKey]} treeData={dirTree} defaultExpandedKeys={[""]}
                        onSelect={keys => {
                            if (keys.length > 0) {
                                setCurTreeKey(keys[0] as string);
                            }
                        }} />
                )}
            </Layout.Sider>
            <Layout.Content style={{ height: "calc(100vh - 60px)", overflowY: "scroll", overflowX: "hidden", backgroundColor: "white", paddingLeft: "10px",paddingRight:"10px" }}>
                {countList.length > 0 && (
                    <Descriptions column={4} bordered>
                        {countList.map(countInfo => (
                            <>
                                <Descriptions.Item label="语言">
                                    {countInfo.lang == "" ? "总计" : countInfo.lang}
                                </Descriptions.Item>
                                <Descriptions.Item label="代码行数">
                                    {countInfo.code}
                                </Descriptions.Item>
                                <Descriptions.Item label="注释行数">
                                    {countInfo.comments}
                                </Descriptions.Item>
                                <Descriptions.Item label="空白行数">
                                    {countInfo.blanks}
                                </Descriptions.Item>
                            </>
                        ))}
                    </Descriptions>
                )}
                {winSize !== undefined && countList.length > 0 && (
                    <>
                        <h2 style={{ fontSize: "20px", fontWeight: 700, marginTop: "10px" }}>代码分布</h2>
                        <PieChart width={winSize.width - 600} height={winSize.width - 600}>
                            <Pie data={countList.filter(item => item.lang != "").map(item => ({ name: item.lang, value: item.code }))}
                                dataKey="value"
                                outerRadius={(winSize.width - 800) / 2}
                                isAnimationActive={false}
                                label={item => `${item.name} ${item.value}`}
                            >
                                {countList.filter(item => item.lang != "").map((countInfo, index) => (
                                    <Cell key={countInfo.lang} fill={COLORS[index % COLORS.length]} />
                                ))}
                            </Pie>
                            <Tooltip />
                        </PieChart>
                    </>
                )}
            </Layout.Content>
        </Layout>
    );
};

export default CountAnalyse;